package utils.commons;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import play.db.jpa.JPA;
import utils.LogUtil;

public class CommonUtils {
	private static Map<TableIndex,Map<String,Long>> idmap = new HashMap<TableIndex,Map<String,Long>>();
	private static Map<String,Map<String,Long>> idmap2 = new HashMap<String,Map<String,Long>>();
	public enum TableIndex{
		station,
		scheduleprice,
		vehicle,
		ticketsell,
		departpassener,
		errorticket,
		orders,
		customer
	}
	
	/**
	 * 获得某表的ID
	 * 根据LocalID取得ID，独立事务，每调用一次自动加1
	 * @param localID 地区编号
	 * @TableIndex 表的索引号
	 * @return 返回一个ID
	 * @throws Exception 
	 */
	public static long GetPKID(TableIndex tableIndex) throws Exception 
	{
		synchronized(tableIndex){
			long PKID=0,id=0;
			long bit=10000000000L;
			Map<String,Long> cim = idmap.get(tableIndex);
			Long currid = null;
			Long endid = null;
			if(cim != null){
				currid = cim.get("currentid");
				endid = cim.get("endid");
				if(currid != null && endid != null && currid < endid){
					currid = currid.longValue()+1;
					cim.put("currentid", currid);
					PKID=(100+tableIndex.ordinal());
					PKID=PKID*bit+currid;
					return PKID;
				}
			}else{
				cim = new HashMap<String,Long>();
				idmap.put(tableIndex, cim);
			}
			
			EntityManager em = null;
			try
			{
				//先增加再取值
				//JPA.em().createNativeQuery("Update PKidentity Set PKID=PKID+1 where TableIndex=1").executeUpdate();
				em = JPA.newEntityManager();
				em.getTransaction().begin();
				Query query = em.createNativeQuery("Update idbuild Set currentid=currentid+100 where tablename=?1");
				query.setParameter(1, tableIndex.name());
				int result = query.executeUpdate(); //影响的记录数
				
				if (result>0)
				{
					//int i=1/0;
					Query querySelect = em.createNativeQuery("Select currentid from idbuild where tablename=:tablename");
					querySelect.setParameter("tablename", tableIndex.name());
					Long rs = Long.valueOf(querySelect.getSingleResult().toString());
					endid = rs.longValue();
					currid = endid-99;
					PKID=(100+tableIndex.ordinal());
					PKID=PKID*bit+currid;
					em.getTransaction().commit();
					//JPA.em().joinTransaction()
					cim.put("currentid",currid);
					cim.put("endid",endid);
					return Long.valueOf(PKID);
				}
				else
				{
					em.getTransaction().rollback();
					//throw new play.exceptions.UnexpectedException(Messages.get("ALERT.REGISTER.GET_ID_ERROR"));
				}
			}catch (Exception e) {
				em.getTransaction().rollback();
				LogUtil.logerror(null, "获得ID号出现错误", e);
				throw e;
			}finally{
				if(em.getTransaction().isActive()){
					em.getTransaction().commit();
				}
				if(em!=null){
					if(em.isOpen()){
						em.close();
					}
				}
			}
			return 0l;
		}
	}

	public static Long GetPKID(String tablename) throws Exception {
		synchronized(tablename){
			long PKID=0,id=0;
			long bit=10000000000L;
			Map<String,Long> cim = idmap2.get(tablename);
			Long currid = null;
			Long endid = null;
			if(cim != null){
				currid = cim.get("currentid");
				endid = cim.get("endid");
				if(currid != null && endid != null && currid < endid){
					currid = currid.longValue()+1;
					cim.put("currentid", currid);
					PKID=1;
					PKID=PKID*bit+currid;
					return PKID;
				}
			}else{
				cim = new HashMap<String,Long>();
				idmap2.put(tablename, cim);
			}
			
			EntityManager em = null;
			try
			{
				//先增加再取值
				//JPA.em().createNativeQuery("Update PKidentity Set PKID=PKID+1 where TableIndex=1").executeUpdate();
				em = JPA.newEntityManager();
				em.getTransaction().begin();
				Query query = em.createNativeQuery("Update idbuild Set currentid=currentid+100 where tablename=?1");
				query.setParameter(1, tablename);
				int result = query.executeUpdate(); //影响的记录数
				
				if (result>0)
				{
					//int i=1/0;
					Query querySelect = em.createNativeQuery("Select currentid from idbuild Where tablename=?1");
					querySelect.setParameter(1, tablename);
					Long rs = Long.valueOf(querySelect.getSingleResult().toString());
					endid = rs.longValue();
					currid = endid-99;
					PKID=1;
					PKID=PKID*bit+currid;
					em.getTransaction().commit();
					//JPA.em().joinTransaction()
					cim.put("currentid",currid);
					cim.put("endid",endid);
					return Long.valueOf(PKID);
				}
				else
				{
					em.getTransaction().rollback();
					//throw new play.exceptions.UnexpectedException(Messages.get("ALERT.REGISTER.GET_ID_ERROR"));
				}
			}catch (Exception e) {
				em.getTransaction().rollback();
				LogUtil.logerror(null, "获得ID号出现错误", e);
				throw e;
			}finally{
				if(em.getTransaction().isActive()){
					em.getTransaction().commit();
				}
				if(em!=null){
					if(em.isOpen()){
						em.close();
					}
				}
			}
			return 0l;
		}
	}

}
